#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#引必要的库，没有的请百度一下，然后通过pip命令来安装一下
import os, sys,string
from kconfiglib import Kconfig
from menuconfig import menuconfig
import json
from datetime import datetime
import os.path

#创建一个全局的字典结构用于读取json，方便处理
user = {

    "input_file_path": "./config.in",
    "output_file_path": "./gen_config.h",
    "defconfig_path":"./defconfig.config",
    "defconfig_header":"./defconfig.h",
    "update_time": True,
    "add_extern_c":True,
    "fg_color":"white",
    "bg_color":"green",
    "encoding":"utf-8",
    "creator":"your name here",
    "first_letter_of_macro":"#",
    "item_prefix":"CONFIG_",
    "description":[],
    "include_libs":[],

}

#读取user.json的配置
def read_user_json():
    # 打开JSON文件并读取内容
    with open("user.json", "r") as file:
        user.update(json.load(file))

#配置kconfig的基本选项
def mconf_set_env():
    """
    Set Kconfig Env
    """
    os.environ["MENUCONFIG_STYLE"] = "default selection=fg:"+user["fg_color"]+",bg:"+user["bg_color"]
    os.environ["KCONFIG_CONFIG"] = os.path.join(user["defconfig_path"])
    os.environ["KCONFIG_CONFIG_HEADER"] = ""
    os.environ["KCONFIG_AUTOHEADER"] = os.path.join(user["defconfig_header"])
    os.environ["CONFIG_"] = user["item_prefix"]

#执行kconfig生成menuconfig界面
def mconfig(argv):
    mconf_set_env()
    kconf = Kconfig(filename=os.getcwd()+user["input_file_path"])
    menuconfig(kconf)
    kconf.write_autoconf()


#主函数
if __name__ == "__main__":

    read_user_json()#先读json到全局的字典变量
    mconfig(sys.argv)#执行menuconfig

    output_file_name = os.path.basename(user["output_file_path"])#获取输出文件名
    output_file = open(user["output_file_path"],"w+",encoding=user["encoding"])#重写输出文件，不管存不存在

    group_str=user["item_prefix"]+"_x_xx_xxx"#分组前缀名初始化

    if(user["update_time"]==True):#加入本次配置的日期时间
        output_file.write("// last update time: "+str(datetime.now())+"\n")
    
    output_file.write("// creator: "+user["creator"]+"\n")#加入作者信息    
    output_file.write("/*" + "\n")  
    for item in user["description"]:#加入描述
        output_file.write("*"+item + "\n")  # 写入每一项并加上换行符
    
    output_file.write("*/" + "\n") 
    #加入头文件的标准宏定义格式
    output_file.write("#ifndef "+output_file_name.upper().replace(".","_")+"\n")
    output_file.write("#define "+output_file_name.upper().replace(".","_")+"\n")
    
    if(user["add_extern_c"]==True):#加入c++需要的extern c
        output_file.write("#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n")
    output_file.write( "\n") 

    #print("include_libs")
    for item in user["include_libs"]:#加入用户需要引入的头文件
        output_file.write(item + "\n")# 写入每一项并加上换行符
    output_file.write("\n") 
    
    with open(user["defconfig_header"],'r', encoding=user["encoding"]) as defconfig_header:
        cnt=0
        for line in iter(defconfig_header.readline, '\n'):
            # 这个if判断必须要加，否则找不到空的换行符
            if len(line) == 0:
                break
            cnt += 1
            
            line_split = line.split(" ")
            # if(line_split==""):
            #     continue
            #分组的判断,按前缀直到下划线出现为止如果前缀相同就是同一个配置
            group_index = group_str[len(user["item_prefix"]):].find('_')
            define_index = line_split[1][len(user["item_prefix"]):].find('_')
            #print(group_str[len(user["item_prefix"]):len(user["item_prefix"])+group_index]+ "=="+line_split[1][len(user["item_prefix"]):len(user["item_prefix"])+define_index])
            if group_str[len(user["item_prefix"]):len(user["item_prefix"])+group_index] != line_split[1][len(user["item_prefix"]):len(user["item_prefix"])+define_index]:
                output_file.write("\n//"+line_split[1][len(user["item_prefix"]):len(user["item_prefix"])+define_index] +"------------------------------------------------------------------------------------------------------------------\r\n")
                # print(line_split[1][len(user["item_prefix"]):len(user["item_prefix"])+define_index])
                group_str=line_split[1]
                is_first_group=False
            value_split = line_split[2].split("\"")
            line= "//"+line_split[1].lower()+"\n"+line_split[0]+" "+line_split[1]+" "+line_split[2]

            if(len(value_split)>1):
                if(value_split[1][0]==user["first_letter_of_macro"]):
                    string_split =value_split[1].split(user["first_letter_of_macro"])  
                    line="//"+line_split[1].lower()+"\n"+line_split[0]+" "+line_split[1]+" "+string_split[1]+"\n"
                    # print(line)     
            output_file.write(line)            
            
    
    if(user["add_extern_c"]==True):#加入c++需要的extern c
        output_file.write("\n#ifdef __cplusplus\n}\n#endif\n")   
    #加入头文件的标准宏定义格式
    output_file.write("\n#endif"+"//"+output_file_name.upper().replace(".","_")+"\n")
    defconfig_header.close()#关闭defconfig
    output_file.close()#关闭输出文件保存
